package com.example.base.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.ListView;

import com.example.base.R;
import com.example.base.adapter.HistoryViewAdapter;
import com.example.base.bean.HistoryBean;
import com.example.base.sqllite.MySQLite;

import java.util.ArrayList;
import java.util.List;

public class HistoryActivity extends AppCompatActivity {
  private ListView listView;
  private HistoryViewAdapter historyViewAdapter;
  private List<HistoryBean> historyBeans;
  private ImageButton imageButton;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_history);
    initView();
    initListener();
    SqliteQuery();
  }

  private void SqliteQuery() {
    MySQLite user = new MySQLite(this, "user", null, 1);
    SQLiteDatabase db = user.getWritableDatabase();
    String query = "select * from history";
    @SuppressLint("Recycle") Cursor cursor = db.rawQuery(query, null);
    ArrayList<HistoryBean> dats = new ArrayList<>();
    while (cursor.moveToNext()) {
      HistoryBean historyBean = new HistoryBean();
      String title = cursor.getString(cursor.getColumnIndex("title"));
      String text = cursor.getString(cursor.getColumnIndex("text"));
      String link = cursor.getString(cursor.getColumnIndex("link"));
      String time = cursor.getString(cursor.getColumnIndex("time"));
      historyBean.setTitle(title);
      historyBean.setText(text);
      historyBean.setLink(link);
      historyBean.setTime(time);
      dats.add(historyBean);
    }
    historyBeans = dats;
    historyViewAdapter = new HistoryViewAdapter(this, historyBeans);
    listView.setAdapter(historyViewAdapter);
    refreshListView(historyBeans);
  }

  private void initView() {
    listView = findViewById(R.id.list_history);
    imageButton = findViewById(R.id.img_history_back);
  }

  private void initListener() {
    imageButton.setOnClickListener(v -> finish());
    listView.setOnItemClickListener((parent, view, position, id) -> {
      Intent intent = new Intent(HistoryActivity.this, WebViewActivity.class);
      intent.putExtra("Url", historyBeans.get(position).getLink());
      startActivity(intent);
    });
  }

  private void refreshListView(List<HistoryBean> historyBeans) {
    historyViewAdapter.setData((ArrayList<HistoryBean>) historyBeans);
    historyViewAdapter.notifyDataSetChanged();
  }
}